#include "StdAfx.h"
#include "MyThread.h"

class ATest
{
public:
	~ATest()
	{
		std::cout << "~ATest" << std::endl;
	}
};

HANDLE m_hMutex;
DWORD WINAPI  MyThreadFunc(LPVOID event)
{
	{
		ATest a;

		std::cout << "Thread start" << std::endl;
		m_hMutex = CreateMutex(NULL, TRUE, NULL);

		HANDLE* handle = reinterpret_cast<HANDLE*>(event);
		WaitForSingleObject(*handle, INFINITE);

		std::cout << "Thread end----" << std::endl;
	}
	::ReleaseMutex(m_hMutex);

	return 0;
}

MyThread::MyThread()
{
    m_mutex = CreateMutex(NULL, TRUE, NULL);

    DWORD dwThreadId = 0;
    m_thread = CreateThread(
        NULL, // default security attributes
        0, // use default stack size 
        MyThreadFunc, // thread function
        &m_mutex, // argument to thread function
        0, // use default creation flags
        &dwThreadId); // returns the thread identifier

    if (m_thread == NULL)
    {
        printf("CreateThread() failed, error: %d.\n", GetLastError());

    }
    else
    {
        printf("It seems the CreateThread() is OK lol!\n");
    }
}

MyThread::~MyThread()
{
    Wait();
	if (CloseHandle(m_mutex) == 0)
	{
		printf("Handle to mutex closed incorrect.\n"); 
	}
	if (CloseHandle(m_hMutex) == 0)
	{
		printf("Handle to thread closed incorrect.\n"); 
	}
}

void MyThread::Stop()
{
    ReleaseMutex(m_mutex);
}

void MyThread::Wait()
{
	Stop();
	WaitForSingleObject(m_hMutex, INFINITE);
	TerminateThread(m_thread, 0);
	WaitForSingleObject(m_thread, INFINITE);
}